<template>
  <div class="store-management-container">
    <div class="header">
      <h3 class="title">商家管理 - 查看店铺</h3>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData" :icon="Refresh">刷新数据</el-button>
      </div>
    </div>

    <el-card class="store-table-card">
      <div class="table-header">
        <el-input
            v-model="searchQuery"
            placeholder="搜索店铺名称或地址"
            clearable
            @clear="handleSearchClear"
            @keyup.enter="handleSearch"
            style="width: 300px; margin-bottom: 15px;"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <el-table
          :data="paginatedData"
          stripe
          style="width: 100%"
          v-loading="loading"
          :empty-text="emptyText"
      >
        <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
        <el-table-column prop="shopName" label="店铺名称" width="180"></el-table-column>
        <el-table-column prop="address" label="店铺地址" show-overflow-tooltip></el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" width="150" align="center"></el-table-column>
        <el-table-column label="店铺头像" width="120" align="center">
          <template #default="scope">
            <el-popover placement="right" :width="200" trigger="hover">
              <template #reference>
                <el-avatar
                    :size="50"
                    :src="scope.row.shopAvatar || defaultAvatar"
                    shape="square"
                    fit="cover"
                />
              </template>
              <div class="avatar-preview">
                <img
                    :src="scope.row.shopAvatar || defaultAvatar"
                    alt="店铺头像"
                    class="preview-image"
                />
                <p class="avatar-text">店铺头像预览</p>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
<!--        <el-table-column label="操作" width="150" align="center">-->
<!--          <template #default="scope">-->
<!--            <el-button-->
<!--                type="primary"-->
<!--                size="small"-->
<!--                @click="handleEdit(scope.row)"-->
<!--                :icon="Edit"-->
<!--            >编辑</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>

      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :small="false"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredData.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :disabled="loading"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { Refresh, Edit, Search } from '@element-plus/icons-vue';

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 从 localStorage 获取用户信息
const userStr = localStorage.getItem('user');
const user = userStr ? JSON.parse(userStr) : null;

// 定义店铺列表
const merchantList = ref([]);
const loading = ref(false);
const searchQuery = ref('');
const emptyText = ref('暂无数据');

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 计算属性：过滤后的数据
const filteredData = computed(() => {
  if (!searchQuery.value) return merchantList.value;

  return merchantList.value.filter(item => {
    return (
        item.shopName.toLowerCase().includes(searchQuery.value.toLowerCase()) ||
        item.address.toLowerCase().includes(searchQuery.value.toLowerCase())
    );
  });
});

// 计算属性：分页后的数据
const paginatedData = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize;
  const end = start + pagination.value.pageSize;
  return filteredData.value.slice(start, end);
});

// 定义查看店铺方法
const selStore = async () => {
  try {
    loading.value = true;
    // 发送查看店铺请求
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selStore`, {
      withCredentials: true
    });

    if (response.data.code === 2000) {
      merchantList.value = response.data.data || [];
      pagination.value.total = merchantList.value.length;
      emptyText.value = merchantList.value.length === 0 ? '暂无店铺数据' : '';
    } else {
      ElMessage.error(response.data.msg || '查看店铺失败');
      merchantList.value = [];
      emptyText.value = '获取店铺数据失败';
    }
  } catch (error) {
    console.error('查看店铺失败:', error);
    ElMessage.error('查看店铺失败，请稍后重试');
    merchantList.value = [];
    emptyText.value = '获取店铺数据失败';
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  pagination.value.currentPage = 1;
  selStore();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  pagination.value.currentPage = 1; // 重置到第一页
};

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val;
};

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1;
};

// 清空搜索
const handleSearchClear = () => {
  searchQuery.value = '';
  pagination.value.currentPage = 1;
};

// 格式化状态
const formatStatus = (status) => {
  return status === 1 ? '营业中' : status === 0 ? '待审核' : '未知';
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  return status === 1 ? 'success' : status === 0 ? 'warning' : 'info';
};

// 编辑店铺
const handleEdit = (row) => {
  // 这里可以添加路由跳转逻辑
  console.log('编辑店铺:', row);
  ElMessage.info(`准备编辑店铺: ${row.shopName}`);
};

// 页面挂载时调用查看店铺方法
onMounted(() => {
  selStore();
});
</script>

<style scoped>
.store-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.store-table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.avatar-preview {
  text-align: center;
  padding: 10px;
}

.preview-image {
  width: 100%;
  height: auto;
  max-height: 200px;
  border-radius: 4px;
  margin-bottom: 8px;
}

.avatar-text {
  font-size: 12px;
  color: #909399;
  margin: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  font-size: 14px;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.el-table :deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>